package org.codehaus.activemq.ra;

import java.lang.reflect.Method;
import javax.jms.ConnectionConsumer;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.resource.ResourceException;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.resource.spi.work.WorkException;
import javax.resource.spi.work.WorkManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class ActiveMQBaseEndpointWorker
{
  private static final Log log = LogFactory.getLog(ActiveMQBaseEndpointWorker.class);
  public static final Method ON_MESSAGE_METHOD;
  protected ActiveMQResourceAdapter adapter;
  protected ActiveMQEndpointActivationKey endpointActivationKey;
  protected MessageEndpointFactory endpointFactory;
  protected WorkManager workManager;
  protected boolean transacted;

  public static void safeClose(Session s)
  {
    try
    {
      if (s != null)
        s.close();
    }
    catch (JMSException e)
    {
    }
  }

  public static void safeClose(ConnectionConsumer cc)
  {
    try
    {
      if (cc != null)
        cc.close();
    }
    catch (JMSException e) {
    }
  }

  public ActiveMQBaseEndpointWorker(ActiveMQResourceAdapter adapter, ActiveMQEndpointActivationKey key) throws ResourceException {
    this.endpointActivationKey = key;
    this.adapter = adapter;
    this.endpointFactory = this.endpointActivationKey.getMessageEndpointFactory();
    this.workManager = adapter.getBootstrapContext().getWorkManager();
    try {
      this.transacted = this.endpointFactory.isDeliveryTransacted(ON_MESSAGE_METHOD);
    } catch (NoSuchMethodException e) {
      throw new ResourceException("Endpoint does not implement the onMessage method.");
    }
  }

  public abstract void start()
    throws WorkException, ResourceException;

  public abstract void stop()
    throws InterruptedException;

  static
  {
    try
    {
      ON_MESSAGE_METHOD = javax.jms.MessageListener.class.getMethod("onMessage", new Class[] { Message.class });
    } catch (Exception e) {
      throw new ExceptionInInitializerError(e);
    }
  }
}